package datasource.temp;

import org.apache.pdfbox.contentstream.PDFStreamEngine;
import org.apache.pdfbox.contentstream.operator.Operator;
import org.apache.pdfbox.contentstream.operator.OperatorName;
import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSString;
import org.apache.pdfbox.pdmodel.PDPageContentStream;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

public class PDFContentProcessor extends PDFStreamEngine {
    private final TextRemover textRemover;
    private final List<Operator> operators = new ArrayList<>();
    private final List<List<COSBase>> operandsList = new ArrayList<>();

    public PDFContentProcessor(TextRemover textRemover) {
        this.textRemover = textRemover;
    }

    @Override
    public void processOperator(Operator operator, List<COSBase> operands) throws IOException {
        if (textRemover.processOperator(operator, operands)) {
            operators.add(operator);
            operandsList.add(new ArrayList<>(operands));
        }
    }

    public void writeTo(PDPageContentStream contentStream) throws IOException {
        contentStream.beginText(); // 开始文本操作
        for (int i = 0; i < operators.size(); i++) {
            Operator operator = operators.get(i);
            List<COSBase> operands = operandsList.get(i);

            if (operator.getName().equals(OperatorName.SHOW_TEXT) ||
                    operator.getName().equals(OperatorName.SHOW_TEXT_LINE) ||
                    operator.getName().equals(OperatorName.SHOW_TEXT_LINE_AND_SPACE)) {
                COSBase base = operands.get(0);
                if (base instanceof COSString) {
                    COSString cosString = (COSString) base;
                    contentStream.showText(cosString.getString()); // 写入文本内容
                }
            }
        }
        contentStream.endText(); // 结束文本操作
    }
}
